package com.itheima.service.mongo;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.UserLocation;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserLocationServiceImpl implements UserLocationService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Long userId, Double longitude, Double latitude, String address) {

        Query query = new Query(Criteria.where("userId").is(userId));

        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);

        //未找到，新增
        if (userLocation == null) {
            userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setAddress(address);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));

            mongoTemplate.save(userLocation);
        } else {
            //更新位置
            userLocation.setUserId(userId);
            userLocation.setAddress(address);
            userLocation.setLastUpdated(userLocation.getUpdated());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));

            mongoTemplate.save(userLocation);
        }

    }



    //查询附近的用户id
    @Override
    public List<Long> findNearUserIdList(Long userId, Long distance) {

        //查询条件
        Query query = new Query(Criteria.where("userId").is(userId));

        //根据查询条件找出自己的位置
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);

        //确定半径
        Distance dis = new Distance(distance / 1000, Metrics.KILOMETERS);

        //画圆
        Circle circle = new Circle(userLocation.getLocation(), dis);

        //查询条件
        Query query1 = new Query(Criteria.where("location").withinSphere(circle));

        //查询附近的人
        List<UserLocation> userLocationList = mongoTemplate.find(query1, UserLocation.class);

        //创建集合储存附近人id
        List<Long> idList = new ArrayList<>();

        //取出id，存入集合
        if (CollectionUtil.isNotEmpty(userLocationList)) {
            for (UserLocation location : userLocationList) {
                idList.add(location.getUserId());
            }
        }

        return idList;
    }
}
